package com.bobi.tfca.ui.mainnavigation.user.password

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.constants.ReplyConstant
import com.bobi.tfca.databinding.FragmentChangePasswordBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MemberAPI
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.ui.app.MainActivity
import com.bobi.tfca.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ChangePasswordFragment : BaseFragment<FragmentChangePasswordBinding, ViewModel>(
    FragmentChangePasswordBinding::inflate,
    null,
    true
) {

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentChangePasswordBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)
        // 设置下一步监听
        binding.btConfirm.setOnClickListener {
            val oldPassword = binding.etOldPassword.text.toString()
            val newPassword = binding.etNewPassword.text.toString()
            val confirmPassword = binding.etConfirmPassword.text.toString()
            if (oldPassword.isNullOrBlank() || newPassword.isNullOrBlank() || confirmPassword.isNullOrBlank()) {
                Toast.makeText(requireActivity(), "账号或密码不能为空", Toast.LENGTH_SHORT).show()
            } else if (!newPassword.equals(confirmPassword)) {
                Toast.makeText(requireActivity(), "两次密码不一致", Toast.LENGTH_SHORT).show()
            } else if (newPassword.length < 8){
                Toast.makeText(requireActivity(), "密码长度必须大于8位", Toast.LENGTH_SHORT).show()
            } else {
                // 创建确认框
                val builder = AlertDialog.Builder(requireContext())
                builder.setTitle("修改密码")
                builder.setMessage("你确认修改密码吗")

                // 设置确认按钮和点击事件
                builder.setPositiveButton("确认") { dialog, which ->
                    changePassword(oldPassword, newPassword)
                }

                // 设置取消按钮和点击事件
                builder.setNegativeButton("取消") { dialog, which ->
                }

                // 创建并显示确认框
                val dialog: AlertDialog = builder.create()
                dialog.show()
            }
        }
    }

    private fun changePassword(oldPassword: String, newPassword: String) {
        publicViewModel!!.apply {
            request(MemberAPI::class.java).changePwByPw(oldPassword, newPassword).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val res = it.data
                                if (res?.code == 200) {
                                    // 清除SharedPreferences里的登录信息
                                    spUtil.clearLoginInfo()
                                    // 清除AppCache
                                    AppCache.setMyInfo(null)
                                    // 断开socket
                                    AppCache.logout()
                                    // 清除token
                                    publicViewModel!!.requestBuilder.authorization(null)
                                    // 重置菜单元素
                                    publicViewModel!!.resetVisiblePageElements()
                                    // 请求元素列表，以便设置可见性
                                    publicViewModel!!.getCurrentAllMenus()
                                    // 重置用途和用户和密码
                                    publicViewModel!!.reply = ReplyConstant.RESET_PASSWORD
                                    // 跳转回复界面
                                    requireActivity().findNavController(R.id.app_nav).navigate(R.id.action_changePasswordFragment_to_replyFragment, null,
                                        NavOptions.Builder().setPopUpTo(R.id.changePasswordFragment, true)
                                            .build())
                                } else {
                                    Toast.makeText(requireActivity(), "账号或密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentChangePasswordBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.visibility = View.GONE
    }


}